package volkov.ja.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map.Entry;
import java.util.TreeMap;
/*
 * database utilities
 */
public class DbUtilities {

	private Connection con;

	public DbUtilities() {
	}

	private boolean connectDb() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			con = DriverManager
					.getConnection("jdbc:mysql://localhost:3306/php4dvd?"
							+ "user=root&password=&characterEncoding=UTF-8");
			if (con != null)
				return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	public Connection con() {
		try {
			if (con == null) {
				connectDb();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public void close() {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void prepareFixture(String name) {
		FixtureLoader fl = new FixtureLoader();
		TreeMap<String, String> queries = fl.getFixtures(name);
		runQueries(queries);
	}

	private void runQueries(TreeMap<String, String> queries) {
		for (Entry<String, String> entry : queries.entrySet()) {
			String sql = entry.getValue();
			PreparedStatement preStatement = null;
			try {
				preStatement = con().prepareStatement(sql);
				preStatement.execute();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (preStatement != null)
					try {
						preStatement.close();
						// con().commit(); // no need for this mysql db
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	}
	
}